Relation with pivot table

  • STEP

    Model

    User.php

    
    
    class User extends Authenticatable
    {
       
        public function roles()
        {
            return $this->belongsToMany(Role::class, 'role_user');
        }
    }
    
    

    Role.php

    
           
    class Role extends Model
    {
        /**
         * The users that belong to the role.
         */
        public function users()
        {
            return $this->belongsToMany(User::class, 'role_user');
        }
    }
    
    

    Retrive the records

    
    $user = User::find(1); dd($user->roles);
    $role = Role::find(1); dd($role->users);
    

    Create the records

    
    $user = User::find(2); $roleIds = [1, 2];$user->roles()->attach($roleIds);
    
    $user = User::find(3); $roleIds = [1, 2];$user->roles()->sync($roleIds);
    
    
    $role = Role::find(1); $userIds = [10, 11];$role->users()->attach($userIds);
    
    
    $role = Role::find(2); $userIds = [10, 11];$role->users()->sync($userIds);
    
    OR

    in Models/Student.php

    
      public function subject()
        {
            return $this->belongstoMany('App\Models\Subject');
        }
      

    in Models/Subject.php

    
      public function student()
        {
            return $this->belongstoMany('App\Models\Student');
        }
      

    Get data

    
      $student = Student::find(1);
            dd($student->subject);
      

    Students who have subjects

    
      $student = Student::has('subject')->get();
            dd($student);
      

    Students who does not have subjects

    
      public function index(){
            $student = Student::doesntHave('subject')->get();
            dd($student);
        }
      

    Students which have a particular subject

    
      public function index(){
            $student = Subject::with('student')->where('id',2)->get();
            dd($student);
        }
      

    Fetch count of subjects each student has

    
      $student = Student::withCount('subject')->get();
            dd($student);
      

    Fetch count of subjects each student has order by subject_count in descending order

    
      $student = Student::withCount('subject')->orderBy('subject_count','desc')->get();
            dd($student);
      

    Fetch students with 2 or more subjects

    
      $student = Student::has('subject','>=',2)->get();
            dd($student);
      

    Fetch students with grade >= 90 , we will use grade in Pivot Table

    
      $student = Student::with('subject')
            ->whereHas('subject', function($query){
                $query->where('grade','>=',90);
            })->get();
            dd($student);